package com.webserver.core;

import com.webserver.controllers.ArticleController;
import com.webserver.controllers.ToolsController;
import com.webserver.controllers.UserController;
import com.webserver.http.HttpContext;
import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 用于处理请求
 */
public class DispatcherServlet {
    public void service(HttpRequest request, HttpResponse response) throws InvocationTargetException, IllegalAccessException {
        /**
         * V16版本的第一个改动，不知再使用uri作为请求路径了，因为若
         * 提交数据，uri中会包含？及参数
         */
        String path = request.getRequestURI();
        //首先判断请求路径是否为请求业务
        HandlerMapping.MethodMapping methodMapping
                = HandlerMapping.getMethodByPath(path);
        if(methodMapping!=null){

            Object controller = methodMapping.getController();
            Method method = methodMapping.getMethod();
            method.invoke(controller,request,response);

        }else {
            File file = new File("./webapps" + path);
            if (file.exists() && file.isFile()) {
                //资源存在
                response.setEntity(file);
            } else {
                //资源不存在
                response.setStatusCode(404);
                response.setStatusReason("NotFound");
                file = new File("./webapps/root/404.html");
                response.setEntity(file);
            }
        }

        response.addHeader("Server","WebServer");


    }
}
